package com.atguigu.gulimall.product.sync.lock;

import java.util.concurrent.locks.ReentrantLock;

public class LockSaleTicket {

    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 40; i++) {
                    ticket.sale();
                }

            }
        }, "AA").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 40; i++) {
                    ticket.sale();
                }

            }
        }, "BB").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 40; i++) {
                    ticket.sale();
                }

            }
        }, "CC").start();

    }


}

class Ticket {
    private int number = 30;
    private final ReentrantLock lock = new ReentrantLock(true);//true公平锁，false非公平锁

    public void sale() {
        lock.lock();
        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + ":卖出" + (number--) + "剩下：" + number);
            }
        } finally {
            lock.unlock();
        }
    }

}